<template>
  <div :id="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/util/util'

export default {
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100px'
    },
    className: {
      type: String,
      default: 'chart'
    },
    visitorData: {
      type: Array,
      default: () => ([])
    },
    otherInfo: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      const that = this
      this.chart.setOption({
        title: {
          text: this.title,
          left:'center',
          top:'35%',
          textStyle:{
            fontSize: 14,
            color: '#ffffff',
            align:'center'
          }
        },
        legend: {
          show: !this.otherInfo,
          type: 'plain',
          orient: 'vertical',
          left: 'center',
          bottom: '2%',
          align: 'left',
          itemGap: 6,
          itemWidth: 10, // 设置宽度
          itemHeight: 10, // 设置高度
          icon:'rect',
          symbolKeepAspect: false,
          formatter: function (name) {
            let total = 0
            let tarValue
            for (let i = 0; i < that.visitorData.length; i++) {
              total += that.visitorData[i].value
              if (that.visitorData[i].name == name) {
                tarValue = that.visitorData[i].value
              }
            }
            let v = Math.trunc((tarValue/total)*100)
           return '{a|'+name+' } '+' {a|'+v+'%  }'+'{a|'+tarValue+'}'
          },
          textStyle:{
            rich:{
              a:{
                color:'#ffffff',
                fontSize:14,
              }
            }
          }
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: [this.otherInfo ? 10 : 30, this.otherInfo ? 60 : 55],
            center: ['50%', this.otherInfo ? '55%' : '40%'],
            roseType: 'radius',
            itemStyle: {
              borderRadius: 1
            },
            label: {
              show: this.otherInfo,
              color: "#fff"
            },
            data: this.visitorData
          }
        ]
      })
    }
  }
}
</script>
